#!/bin/bash

# MySQL故障切换脚本

MASTER_HOST="mysql-master"
BACKUP_HOST="mysql-backup"
MASTER_PORT=3306
BACKUP_PORT=3306

LOG_FILE="./failover.log"

log() {
    echo "$(date): $1" | tee -a $LOG_FILE
}

# 检查主库状态
check_master() {
    docker exec $MASTER_HOST mysqladmin ping -h localhost -u root -proot123 --silent > /dev/null 2>&1
    return $?
}

# 检查备库状态
check_backup() {
    docker exec $BACKUP_HOST mysqladmin ping -h localhost -u root -proot123 --silent > /dev/null 2>&1
    return $?
}

# 主库故障时切换到备库
if ! check_master; then
    log "主库故障，开始故障切换..."
    
    if check_backup; then
        # 停止备库复制
        docker exec $BACKUP_HOST mysql -u root -proot123 -e "STOP REPLICA;"
        
        # 设置备库为可写
        docker exec $BACKUP_HOST mysql -u root -proot123 -e "SET GLOBAL read_only = 0; SET GLOBAL super_read_only = 0;"
        
        log "故障切换完成，备库已提升为主库"
        
        # 发送告警（可以集成邮件、短信等）
        echo "MySQL主库故障，已自动切换到备库" | mail -s "MySQL故障切换告警" admin@example.com
    else
        log "备库也故障，无法进行故障切换"
        exit 1
    fi
else
    log "主库状态正常"
fi
